import React, { useRef, useEffect, useState, useCallback, useMemo } from 'react';
import { View, ScrollView } from '@tarojs/components';
import { VirtualScrollCore, VirtualScrollProps, VirtualScrollItem } from '@repo/virtual-scroll';

// Taro 版本的虚拟滚动组件
export function VirtualScroll<T = any>(props: VirtualScrollProps<T>) {
  const {
    items,
    height,
    estimatedItemHeight,
    overscan = 5,
    waterfall = false,
    waterfallColumns = 2,
    waterfallGap = 10,
    getItemId,
    renderItem,
    calculateHeight,
    onScroll,
    onVisibleItemsChange,
    className,
    style,
  } = props;

  const containerRef = useRef<any>(null);
  const [scrollTop, setScrollTop] = useState(0);
  const [visibleItems, setVisibleItems] = useState<VirtualScrollItem<T>[]>([]);
  const [containerWidth, setContainerWidth] = useState(0);

  // 创建虚拟滚动核心实例
  const virtualScroll = useMemo(() => {
    return new VirtualScrollCore({
      height,
      estimatedItemHeight,
      overscan,
      waterfall,
      waterfallColumns,
      waterfallGap,
    });
  }, [height, estimatedItemHeight, overscan, waterfall, waterfallColumns, waterfallGap]);

  // 更新数据源
  useEffect(() => {
    virtualScroll.updateItems(items, getItemId, calculateHeight);
  }, [items, getItemId, calculateHeight, virtualScroll]);

  // 设置容器宽度（瀑布流需要）
  useEffect(() => {
    if (waterfall) {
      // 在 Taro 中，我们需要通过其他方式获取容器宽度
      // 暂时使用一个默认值，或者通过 props 传入
      const defaultWidth = 375; // 默认屏幕宽度
      setContainerWidth(defaultWidth);
      virtualScroll.setContainerWidth(defaultWidth);
    }
  }, [waterfall, virtualScroll]);

  // 处理滚动事件
  const handleScroll = useCallback((event: any) => {
    const newScrollTop = event.detail.scrollTop || 0;
    setScrollTop(newScrollTop);
    onScroll?.(newScrollTop);
  }, [onScroll]);

  // 更新可见项目
  useEffect(() => {
    const newVisibleItems = virtualScroll.getVisibleItems(scrollTop, height);
    setVisibleItems(newVisibleItems);
    onVisibleItemsChange?.(newVisibleItems);
  }, [scrollTop, height, virtualScroll, onVisibleItemsChange]);

  // 获取总高度
  const totalHeight = useMemo(() => {
    return virtualScroll.getTotalHeight();
  }, [virtualScroll, items]);

  // 渲染可见项目
  const renderVisibleItems = () => {
    return visibleItems.map((item) => {
      const itemStyle: React.CSSProperties = {
        position: 'absolute',
        top: item.top || 0,
        left: waterfall ? (item.left || 0) : 0,
        width: waterfall ? (item.width || 'auto') : '100%',
        height: item.height || estimatedItemHeight,
      };

      return (
        <View
          key={item.id}
          style={itemStyle}
          className="virtual-scroll-item"
        >
          {renderItem(item)}
        </View>
      );
    });
  };

  const containerStyle: React.CSSProperties = {
    height,
    position: 'relative',
    ...style,
  };

  return (
    <ScrollView
      ref={containerRef}
      className={`virtual-scroll-container ${className || ''}`}
      style={containerStyle}
      scrollY
      onScroll={handleScroll}
    >
      <View
        className="virtual-scroll-content"
        style={{
          height: totalHeight,
          position: 'relative',
        }}
      >
        {renderVisibleItems()}
      </View>
    </ScrollView>
  );
}

// 重新导出类型
export type { VirtualScrollProps, VirtualScrollItem } from '@repo/virtual-scroll';
